package ThreadPoolExecutors;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:34398
 * Date:2024-07-27
 * Time:10:19
 */


class MyThreadPool_ {

    //定义一个工作队列，把submit的任务放到队列，线程池拿任务，也在这里区，容量顶一个1000
    BlockingQueue<Runnable> workingQueue = new ArrayBlockingQueue<>(1000);

    //设置结束标志位
    private boolean isShutDown = false;

    //设定固定容量的线程的构造方法
    public MyThreadPool_(int capacity) throws InterruptedException {
        for (int i = 0; i < capacity; i++) {

            Thread t = new Thread(() -> {//线程池固定创建capacity个线程
                while (!isShutDown) {//在线程中，死循环，去take任务
                    Runnable r = null;
                    try {
                        r = workingQueue.take();//从工作队列里面获取任务，没有任务会进入阻塞状态(WAITING)
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    r.run();//执行任务
                }
            });
            t.start();//启动线程
        }
    }

    public void submit(Runnable r) throws InterruptedException {
        workingQueue.put(r);//把任务放到工作队列中
    }

    public void ShutDown(){
        this.isShutDown=true;
    }

}

public class TestCSDNDemo {
    public static void main(String[] args) throws InterruptedException {

        //线程池的线程数设置成10个
        MyThreadPool_ myThreadPool = new MyThreadPool_(10);

        //测试，提交1000个任务
        for (int i = 0; i < 1000; i++) {
            int id = i;
            myThreadPool.submit(() -> {
                Thread currentThread = Thread.currentThread();
                System.out.println("执行任务：" + id + ",线程名字：" + currentThread.getName());
            });
        }

        Thread.sleep(2000);
        myThreadPool.ShutDown();
    }
}
